package com.example.tcp.server;

import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;
import lombok.Data;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

@Data
public class PushPromise {
    private Object obj;
    private Timeout timeout;
    private CompletableFuture<Object> future;

    private static final HashedWheelTimer TIMER = new HashedWheelTimer();

    public PushPromise(Object obj, long timeoutMs) {
        this.obj = obj;
        this.future = new CompletableFuture<>();
        this.timeout = TIMER.newTimeout(new TimerTask() {
            @Override
            public void run(Timeout timeout) throws Exception {
                if(!timeout.isCancelled()) {
                    future.completeExceptionally(new TimeoutException());
                }
            }
        }, timeoutMs, TimeUnit.MICROSECONDS);
    }
}
